<template>
	<view class="app">
		<view class="price-box">
			<text>支付金额</text>
			<text class="price">{{payOrder.realMoney}}</text>
		</view>

		<view class="pay-type-list">
			<!-- #ifdef APP-PLUS || H5 -->
			<view v-if="payTypeOpen.indexOf('pay_alipay') >= 0" class="type-item b-b" @click="changepayType('alipay')">
				<text class="icon xyicon xyicon-alipay"></text>
				<view class="con">
					<text class="tit">{{payTypeList.alipay.title}}</text>
					<text>{{payTypeList.alipay.subtitle}}</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == "alipay"' />
					</radio>
				</label>
			</view>
			<!-- #endif -->
			<!-- #ifdef APP-PLUS || MP-WEIXIN || H5 -->
			<view v-if="payTypeOpen.indexOf('pay_wxpay') >= 0" class="type-item b-b" @click="changepayType('wxpay')">
				<text class="icon xyicon xyicon-wxpay"></text>
				<view class="con">
					<text class="tit">{{payTypeList.wxpay.title}}</text>
					<text>{{payTypeList.wxpay.subtitle}}</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == "wxpay"' />
					</radio>
				</label>
			</view>
			<!-- #endif -->
			<view v-if="payTypeOpen.indexOf('pay_score1') >= 0" class="type-item" @click="changepayType('score1')">
				<text class="icon xyicon xyicon-card"></text>
				<view class="con">
					<text class="tit">{{payTypeList.score1.title}}</text>
					<text>可用余额 ¥{{scoreInfo[1].balance}}</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == "score1"' />
					</radio>
				</label>
			</view>
			<!-- 上门自提不允许货到付款 -->
			<view v-if="payTypeOpen.indexOf('pay_deliver') >= 0 && orderList[0].deliverType != 3"
				class="type-item" @click="changepayType('deliver')">
				<text class="icon xyicon xyicon-received text-error"></text>
				<view class="con">
					<text class="tit">{{payTypeList.deliver.title}}</text>
					<text>收货时当场付款</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == "deliver"' />
					</radio>
				</label>
			</view>
		</view>
		<text class="mix-btn" @click="confirm">确认支付</text>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	export default {
		data() {
			return {
				tradeNo: '',
				payType: '',
				payPlatform: '',
				payOrder: {},
				orderList: [],
				scoreInfo: {
					1: {
						balance: 0.00
					}
				},
				payTypeOpen: [], // 开通的支付方式
				payTypeList: {
					alipay: {
						title: '支付宝支付',
						subtitle: '蚂蚁金服旗下'
					},
					wxpay: {
						title: '微信支付',
						subtitle: '推荐使用微信支付'
					},
					score1: {
						title: '余额支付'
					},
					deliver: {
						title: '货到付款'
					}
				}
			};
		},
		computed: {
			...mapState(['app', 'user'])
		},
		async onLoad(options) {
			this.tradeNo = options.tradeNo;
			let res = await this.util.request({
				url: '/v1/pay/order/pay?tradeNo=' + this.tradeNo,
				method: 'get'
			});
			if (res.code == 200) {
				this.payOrder = res.data.payOrder;
				if (res.data.payTypeOpen) {
					this.payTypeOpen = res.data.payTypeOpen;
				}
				this.orderList = res.data.orderList;
				this.scoreInfo = res.data.scoreInfo;
			} else {
				this.util.showToast({
					title: res.msg,
					icon: 'loading',
					duration: 2000
				});
			}
			
			// 默认选中的支付方式
			console.log(this.payTypeOpen)
			let defaultPayType = this.payTypeOpen[0].split('_');
			console.log(defaultPayType);
			this.payType = defaultPayType[1];

			// 判断支付平台
			// #ifdef APP-PLUS
			this.payPlatform = 'app';
			// #endif
			// #ifdef MP
			this.payPlatform = 'mapp';
			// #endif
			// #ifdef H5
			console.log(this.app.runEnv);
			if (this.app.runEnv == 'weixin-h5') {
				this.payPlatform = 'mp';
			} else if(this.app.runEnv == 'pc-h5') {
				this.payPlatform = 'pc';
			} else {
				this.payPlatform = 'wap';
			}
			// #endif
		},
		methods: {
			// 选择支付方式
			changepayType(type) {
				this.payType = type;
			},
			// 确认支付
			confirm: async function() {
				uni.showLoading({
					title: '请求中...'
				});
				let that = this;
				if (this.payType == 'score1' && this.scoreInfo[1].balance < this.payOrder.realMoney) {
					this.util.showToast({
						title: '余额不足',
						icon: 'loading',
						duration: 1000
					});
					return ;
				}
				let deliverPay = 0;
				if (this.payType == 'deliver') {
					deliverPay = 1;
				}
				let res = await this.util.request({
					url: '/v1/pay/order/dopay',
					method: 'post',
					data: {
						tradeNo: this.tradeNo,
						payType: this.payType,
						deliverPay: deliverPay, // 是否货到付款
						payPlatform: this.payPlatform
					}
				});
				if (res.code == 200) {
					if (res.data.paySuccess) {
						uni.hideLoading();
						uni.redirectTo({
							url: '/pages/ishop/order/paySuccess'
						});
					} else if (res.data.url) { // 支持货到付款
						uni.hideLoading();
						uni.redirectTo({
							url: '/pages' + res.data.url
						});
					} else {
						// 调用本地支付SDK
						console.log(res);
						switch (this.payPlatform){
							case 'app':
								uni.requestPayment({
									provider: this.payType,
									orderInfo: res.data.payString, //微信、支付宝订单数据
									success: function (res) {
										uni.hideLoading();
										uni.redirectTo({
											url: './paySuccess'
										});
									},
									fail: function (err) {
										uni.hideLoading();
										console.log(err);
										let errMsg = '';
										switch (err.errMsg) {
											case 'requestPayment:fail canceled':
												errMsg = '已取消支付';
												break;
											default:
												errMsg = err.errMsg;
												break;
										}
										uni.showModal({
										    title: '提示',
										    content: '支付失败' + errMsg,
										    success: function (res) {
										        if (res.confirm) {
										        } else if (res.cancel) {
										        }
										    }
										});
										return false;
									}
								});
								break;
							case 'mapp':
								let params = {
									provider: this.payType,
									orderInfo: res.data.payString,
									success: function(res){
										uni.hideLoading();
										uni.redirectTo({
											url: './paySuccess'
										});
									},
									fail: function(err){
										uni.hideLoading();
										uni.showModal({
										    title: '提示',
										    content: '支付失败' + JSON.stringify(err),
										    success: function (res) {
										        if (res.confirm) {
										        } else if (res.cancel) {
										        }
										    }
										});
										return false;
									}
								};
								// #ifdef MP-WEIXIN
								let tmp = {
									timeStamp: res.data.payString.timeStamp,
									nonceStr: res.data.payString.nonceStr,
									package: res.data.payString.package,
									signType: res.data.payString.signType,
									paySign: res.data.payString.paySign
								}
								params = Object.assign(params, tmp);
								// #endif
								uni.requestPayment(params);
								uni.hideLoading();
								break;
							case 'pc':
								if (res.data.isRedirect) {
									window.open(res.data.payString);
								} else {
									// 主要针对微信PC端扫码支持，用payString生成二维码给用户扫码支付
								}
								break;
							case 'wap':
								window.open(res.data.payString);
								break;
							case 'mp': // 微信公众号支付
								wx.ready(function(){
									wx.chooseWXPay({
										timestamp: res.data.payString.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
										nonceStr: res.data.payString.nonceStr, // 支付签名随机串，不长于 32 位
										package: res.data.payString.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
										signType: res.data.payString.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
										paySign: res.data.payString.paySign, // 支付签名
										success: function (res) {
											uni.hideLoading();
											uni.redirectTo({
												url: './paySuccess'
											});
										},
										fail: function(err){
											uni.hideLoading();
											uni.showModal({
											    title: '提示',
											    content: '支付失败' + JSON.stringify(err),
											    success: function (res) {
											        if (res.confirm) {
											        } else if (res.cancel) {
											        }
											    }
											});
											return false;
										}
									});
								});
								break;
							default :
								uni.showModal({
									title: '提示',
									content: '不存在该支付方式',
									success: function (res) {
										if (res.confirm) {
										} else if (res.cancel) {
										}
									}
								});
								break;
						}
					}
				} else {
					uni.showModal({
					    title: '提示',
					    content: res.msg,
					    success: function (res) {
					        if (res.confirm) {
					        } else if (res.cancel) {
					        }
					    }
					});
				}
			},
		}
	}
</script>

<style lang='scss'>
	.app {
		width: 100%;
	}

	.price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price{
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;
			&:before{
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;
		.type-item{
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position:relative;
		}
		.xyicon {
			width: 100upx;
			font-size: 52upx;
		}
		.xyicon-card {
			color: #fe8e2e;
		}
		.xyicon-wxpay {
			color: #36cb59;
		}
		.xyicon-alipay {
			color: #01aaef;
		}
		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}
		.con{
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}
	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: $uni-color-primary;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}

</style>
